package brand

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	"insighttracking/query/dao"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyBrandByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewModifyBrandByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ModifyBrandByIdApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyBrandByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ModifyBrandByIdApiLogic) ModifyBrandByIdApi(req *types.ModifyBrandReq) (resp string, err error) {
	_, err = dao.BrandEntity.WithContext(l.ctx).Where(dao.BrandEntity.ID.Eq(req.Id)).First()
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("传递的id错误")
	}
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	supplierEntity, err := dao.BrandEntity.WithContext(l.ctx).Where(
		dao.BrandEntity.Name.Eq(req.Name),
		dao.BrandEntity.EnterpriseID.Eq(enterpriseId),
	).First()
	if !errors.Is(err, gorm.ErrRecordNotFound) && supplierEntity.ID != req.Id {
		return "", errors.New("当前名称存在,不能重复")
	}
	if _, err = dao.BrandEntity.WithContext(l.ctx).Where(dao.BrandEntity.ID.Eq(req.Id)).UpdateSimple(
		dao.BrandEntity.Name.Value(req.Name),         // 单位名称
		dao.BrandEntity.Sort.Value(req.Sort),         // 排序
		dao.BrandEntity.Describe.Value(req.Describe), // 描述
	); err != nil {
		return "", errors.New("修改失败")
	}
	return "修改成功", nil
}
